package net.bungaeting.client.android.activity;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class GroupManageActivity extends Activity {
	private static final String KEY_PREF = "group";
	
	SimpleAdapter leftAdapter;
	SimpleAdapter rightAdapter;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.groupmanage);
        
        SharedPreferences pref = getSharedPreferences(KEY_PREF, 0);
        
        Bungae_DB mHelper = new Bungae_DB(this);
		SQLiteDatabase db = mHelper.getWritableDatabase();
        
        TextView groupName = (TextView)findViewById(R.id.groupName);
        groupName.setText(pref.getString("group", null));
        
        final ArrayList<HashMap<String, String>> leftArray = new ArrayList<HashMap<String, String>>();			// 전화번호부의 이름을 저장할 배열 선언
		//final ArrayList<Group_phone> phone = new ArrayList<Group_phone>();
		final ArrayList<HashMap<String, String>> rightArray = new ArrayList<HashMap<String, String>>();
		//final ArrayList<Group_phone> phoneRight = new ArrayList<Group_phone>();
		
        Cursor rightCursor = db.rawQuery("SELECT _id FROM groupInfo WHERE groupName='" + pref.getString("group", null) + "'", null);
        rightCursor.moveToFirst();
        rightCursor = db.rawQuery("SELECT userName, userPhone FROM groupUserInfo WHERE groupInfo_inx='" + rightCursor.getInt(0) + "'", null);
        
        if(rightCursor.moveToFirst()) 
		{
        	int count = 0;	
        	
        	do 
			{
	        	HashMap<String, String> item = new HashMap<String, String>();
				item.put("name", rightCursor.getString(0));
				item.put("phone", rightCursor.getString(1));
				
				rightArray.add(item);
				
				count++;
			} while(rightCursor.moveToNext() || count > rightCursor.getCount());
		}
		
		Cursor cursor = getURI();					// 전화번호부 가져오기	
		
		if(cursor.moveToFirst()) 
		{
			int count = 0;	
			//int idIndex = cursor.getColumnIndex("_id");	// 컬럼명으로 컬럼 인덱스 찾기 

			do 
			{
				//db.execSQL("INSERT INTO product VALUES (null, '"+ cursor.getString(1) +"', 900);");
				//int id = cursor.getInt(idIndex);	// 요소값 얻기		
				//groupPhone.name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
				//groupPhone.phone = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
				
				if(!rightArray.toString().contains(cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME)))) {
					HashMap<String, String> item = new HashMap<String, String>();
					item.put("name", cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME)));
					item.put("phone", cursor.getString(cursor.getColumnIndex(Phone.NUMBER)));
					
					leftArray.add(item);
					
					count++;
				}
				
			} while(cursor.moveToNext() || count > cursor.getCount());
		}
        
		leftAdapter = new SimpleAdapter(this, leftArray, R.layout.row, new String[] { "name" }, new int[] { R.id.label });
		rightAdapter = new SimpleAdapter(this, rightArray, R.layout.row, new String[] { "name" }, new int[] { R.id.label });
		
		//final ArrayAdapter<Group_phone> leftAdapter = new ArrayAdapter<Group_phone>(this, R.layout.row, R.id.label, name);
		//final ArrayAdapter<Group_phone> rightAdapter = new ArrayAdapter<Group_phone>(this, R.layout.row, R.id.label, nameRight);
		
        ListView left = (ListView)findViewById(R.id.left_list);
        left.setAdapter(leftAdapter);
        left.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
        ListView right = (ListView)findViewById(R.id.right_list);
        right.setAdapter(rightAdapter);
        right.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        
	    left.setOnItemClickListener(new ListView.OnItemClickListener() {
	    	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	    		HashMap<String, String> leftItem = new HashMap<String, String>();
	    		leftItem.put("name", leftAdapter.getItem(position).toString().substring(leftAdapter.getItem(position).toString().lastIndexOf("=")+1, leftAdapter.getItem(position).toString().length()-1));
	    		leftItem.put("phone", leftAdapter.getItem(position).toString().substring(leftAdapter.getItem(position).toString().indexOf("=")+1, leftAdapter.getItem(position).toString().indexOf(",")));
	    		
	    		rightArray.add(leftItem);
	    		leftArray.remove(position);
	    		
	    		//nameRight.add(leftAdapter.getItem(position));
	    		
	    		//Toast.makeText(getApplicationContext(), Integer.toString(position), Toast.LENGTH_SHORT).show();
	    		//Toast.makeText(getApplicationContext(), leftAdapter.getItem(position).toString().substring(leftAdapter.getItem(position).toString().indexOf("=")+1, leftAdapter.getItem(position).toString().indexOf(",")), Toast.LENGTH_SHORT).show();
    				    		
	    		rightAdapter.notifyDataSetChanged();
	    		leftAdapter.notifyDataSetChanged();
	    	}
	    });
	    
	    right.setOnItemClickListener(new ListView.OnItemClickListener() {
	    	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	    		//name.add(rightAdapter.getItem(position));
	    		HashMap<String, String> rightItem = new HashMap<String, String>();
	    		rightItem.put("name", rightAdapter.getItem(position).toString().substring(rightAdapter.getItem(position).toString().lastIndexOf("=")+1, rightAdapter.getItem(position).toString().length()-1));
	    		rightItem.put("phone", rightAdapter.getItem(position).toString().substring(rightAdapter.getItem(position).toString().indexOf("=")+1, rightAdapter.getItem(position).toString().indexOf(",")));
	    		
	    		leftArray.add(rightItem);
	    		rightArray.remove(position);
	    		
	    		rightAdapter.notifyDataSetChanged();
	    		leftAdapter.notifyDataSetChanged();
	    	}
	    });
	}
	
	public Cursor getURI(){
		// 주소록 URI		
		Uri people = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;;
		
		// 검색할 컬럼 정하기
		//String[] projection = new String[] { Contacts.People._ID, Contacts.People.DISPLAY_NAME, Contacts.People.NUMBER };
		
		// 쿼리 날려서 커서 얻기
		//String[] selectionArgs = null;
		String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;	

		return managedQuery(people, null, null, null, sortOrder);
	}
	
	public void groupUserBackClick(View v) {
		Intent groupIndent = new Intent(this, GroupActivity.class);
		startActivity(groupIndent);
	}
	
	public void groupUserAddClick(View v) {
		Bungae_DB mHelper = new Bungae_DB(this);
		SQLiteDatabase db = mHelper.getWritableDatabase();
		
		SharedPreferences pref = getSharedPreferences(KEY_PREF, 0);
		
		Cursor cursor = db.rawQuery("SELECT _id FROM groupInfo WHERE groupName='" + pref.getString("group", null) + "'", null);
		cursor.moveToFirst();
		
		//Toast.makeText(getApplicationContext(), Integer.toString(cursor.getInt(0)), Toast.LENGTH_SHORT).show();
				
		db.execSQL("DELETE FROM groupUserInfo WHERE groupInfo_inx ='" + cursor.getInt(0) + "'");
		
		for(int i=0; i<rightAdapter.getCount(); i++)
			db.execSQL("INSERT INTO groupUserInfo VALUES (null, '"+ cursor.getInt(0) +"', '" + 
					rightAdapter.getItem(i).toString().substring(rightAdapter.getItem(i).toString().lastIndexOf("=")+1, rightAdapter.getItem(i).toString().length()-1) + "', '" +
					rightAdapter.getItem(i).toString().substring(rightAdapter.getItem(i).toString().indexOf("=")+1, rightAdapter.getItem(i).toString().indexOf(",")) + "');");
		
		Intent groupIndent = new Intent(this, GroupActivity.class);
		startActivity(groupIndent);
	}	
}
